package com.wd.visitor.common.service;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wd.visitor.common.domain.dto.EventQuery;
import com.wd.visitor.common.domain.dto.request.ApiRequest;
import com.wd.visitor.common.domain.dto.request.ImageListRequest;
import com.wd.visitor.common.domain.dto.response.ApiResponse;
import com.wd.visitor.common.domain.dto.response.ImageListResponse;
import com.wd.visitor.common.utils.HttpUtils;
import com.wd.visitor.common.utils.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static com.wd.visitor.common.constants.ApiConstant.*;

/**
 * @className: ImageService
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2024/11/3
 **/
@Service
public class ImageService {

    private final static Logger logger = LoggerFactory.getLogger(ImageService.class);

    @Resource
    TokenService tokenService;

    public ImageListResponse getImageList(EventQuery eventQuery) {

        String token = tokenService.getToken();

        ApiRequest<ImageListRequest> imgListParam = new ApiRequest<>();

        imgListParam.getBasic().setToken(token);

        ImageListRequest imageListRequest = new ImageListRequest();
        imageListRequest.setOffset(eventQuery.getStart_no());
        imageListRequest.setSize(eventQuery.getQry_len());
        List<Integer> channelIds = new ArrayList<>();
        imageListRequest.setChannel_ids(channelIds);
        imageListRequest.setStart_time(TimeUtils.parseTimestamp(eventQuery.getStart_time()));
        imageListRequest.setEnd_time(TimeUtils.parseTimestamp(eventQuery.getStop_time()));


        ImageListRequest.ByEvent byEvent = new ImageListRequest.ByEvent();
        List<String> envList = new ArrayList<>();
        envList.add("bed");
        byEvent.setEvent_array(envList);
        imageListRequest.setBy_event(byEvent);

        imgListParam.setData(imageListRequest);
        String post = HttpUtils.post(IMG_LIST, imgListParam.toString());
        logger.info(IMG_LIST + "  Response:" + post);

        if (post != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            ApiResponse<ImageListResponse> apiResponse = null;
            try {
                apiResponse = objectMapper.readValue(post, new TypeReference<ApiResponse<ImageListResponse>>() {
                });

            } catch (IOException e) {
                logger.info("Query Param" + imgListParam.toString());
            }
            return apiResponse.getData();
        }
        return null;


    }


    public static void main(String[] args) {
        ImageListResponse imageList = new ImageService().getImageList(null);
        System.out.println(JSONObject.toJSONString(imageList.getData()));
    }


    public byte[] downloadImage(String file) throws IOException {

        String token = tokenService.getToken();
        if (file.contains(" ")) {
            logger.info(file);
            logger.info("Have space!");
            file = file.replace(" ", "+");
            logger.info(file);
        }


        String urlWithParams = String.format("%s?token=%s&url=%s", IMG_API, token, file);


//        String encodedParam = URLEncoder.encode(urlWithParams, "UTF-8");

        String imageUrl = BASE_IMG_API + urlWithParams;


        logger.info("Get Image:" + imageUrl);

        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();


        // 检查响应码
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            try (InputStream inputStream = connection.getInputStream();
                 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                }
                return byteArrayOutputStream.toByteArray();
            }
        } else {
            logger.info("Failed to download image: " + connection.getResponseCode());
//            logger.info("Failed to download image: " + connection.getResponseMessage());
            // throw new IOException("Failed to download image: " + connection.getResponseCode() + ":" + file);
            return new byte[5];
        }
    }


}
